package bookTrading.buyer;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import java.math.BigDecimal;
import java.text.DecimalFormat;

@SuppressWarnings("serial")
public class BuyerPropose extends CyclicBehaviour
{
	public static Double valorAnterior = null;
	private AgentBuyer agentBuyer;


	// Construtor
	public BuyerPropose(AgentBuyer agentBuyer)
	{
		this.agentBuyer = agentBuyer;
	}


	@Override
	public void action()
	{
		MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.PROPOSE);
		ACLMessage msg = agentBuyer.receive(mt);

		if (msg != null)
		{
			ACLMessage reply = msg.createReply();
			
			Double valorProposto = Double.parseDouble(msg.getContent());

			DecimalFormat df = new DecimalFormat("#,###.00");
			System.out.println("[Propose] Vendedor ofereceu: R$ " + df.format(valorProposto));

			Double valorTmp;
			if (valorAnterior == null)
				valorTmp = 10.0;
				//valorTmp = valorProposto / 2; // Metade do Valor Inicial do Livro
			else
				valorTmp = valorAnterior + (valorProposto / 10); // Adiciona +10%


			if (valorAnterior != null)
			{
				if (valorTmp <= valorAnterior)
				{
					reply.setPerformative(ACLMessage.ACCEPT_PROPOSAL);
					reply.setContent(String.valueOf(valorTmp));
				}
				else
				{
					BigDecimal b = new BigDecimal(valorTmp);
					valorAnterior = Double.parseDouble(String.valueOf(b.setScale(2, BigDecimal.ROUND_DOWN)));
					
					// Comprador faz a Contra-Proposta
					reply.setPerformative(ACLMessage.PROPOSE);
					reply.setContent(String.valueOf(valorAnterior));
				}
			}
			else
			{
				BigDecimal b = new BigDecimal(valorTmp);
				valorAnterior = Double.parseDouble(String.valueOf(b.setScale(2, BigDecimal.ROUND_DOWN)));
				
				// Comprador faz a Contra-Proposta
				reply.setPerformative(ACLMessage.PROPOSE);
				reply.setContent(String.valueOf(valorAnterior));
			}
			
			agentBuyer.send(reply);
		}
		else
			block();
	}
}